﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using ERP_RORZE_SYSTEM;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ERP_RORZE_DLL.Assembly
{
    public partial class frm_F4Export : Form
    {
        private List<string> serialList;
        public frm_F4Export()
        {
            InitializeComponent();
            this.mySetting = new INISettings();
            this.myConnection = new SqlConnection(mySetting.SQLConnectionString);
            serialList = new List<string>();      
            this.dtExportDate.EditValue = DateTime.Now.Date;
            getCompIDList();
            this.cbeCompID.Properties.AutoComplete = true;
            getCustomerList();
            this.cbeCustomerID.Properties.AutoComplete = true;
            this.cbeCompID.SelectedIndexChanged += cbeCompID_SelectedIndexChanged;
            this.cbeCompID.TextChanged += cbeCompID_TextChanged;
        }

        void cbeCompID_TextChanged(object sender, EventArgs e)
        {            
            if (!string.IsNullOrEmpty(this.cbeCompID.Text.Trim()))
            {                
                for (int i = 0; i < this.cbeCompID.Properties.Items.Count; i++)
                {
                    ComboboxItem item = (ComboboxItem)this.cbeCompID.Properties.Items[i];
                    if (item.Value.ToString() == this.cbeCompID.Text.Trim())
                    {
                        this.cbeCompID.SelectedIndex = i;
                    }
                }
            }
        }

        
        ////////////////////////////////////////////////
        /// Load Order No list to form
        ////////////////////////////////////////////////
        private void getCompIDList()
        {
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT DISTINCT CompID AS CompID"
                    + " FROM [231_RobotOrderDetail] WHERE Exported=0 ORDER BY CompID";
                SqlDataReader dataReader = cmd_sql.ExecuteReader();
                while (dataReader.Read())
                {                    
                    ComboboxItem item = new ComboboxItem();
                    item.Text = dataReader["CompID"].ToString();                    
                    item.Value = dataReader["CompID"].ToString();
                    this.cbeCompID.Properties.Items.Add(item);
                }
                dataReader.Close();
                cmd_sql.Dispose();
                myConnection.Close();
            }
            catch //(Exception ex)
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                //MessageBox.Show(ex.Message);
                MessageBox.Show("Cannot get Comp list");
            }
        }


        ////////////////////////////////////////////////
        /// Load Customer list to combobox
        ////////////////////////////////////////////////
        private void getCustomerList()
        {
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT CustomerID FROM [231_Customer] ORDER BY CustomerID";
                SqlDataReader dataReader = cmd_sql.ExecuteReader();
                while (dataReader.Read())
                {
                    ComboboxItem item = new ComboboxItem();
                    item.Text = dataReader["CustomerID"].ToString();
                    item.Value = dataReader["CustomerID"].ToString();
                    this.cbeCustomerID.Properties.Items.Add(item);
                }
                dataReader.Close();
                cmd_sql.Dispose();
                myConnection.Close();
            }
            catch //(Exception ex)
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                //MessageBox.Show(ex.Message);
                MessageBox.Show("Cannot get Customer list");
            }
        } 

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            this.Dispose();
        }        
        
        ///////////////////////////
        /// When Click Add Button
        ///////////////////////////        
        private void buttonAdd_Click(object sender, EventArgs e)
        {
            string error = null;
            DateTime exporteddate;
            string comp = null;
            string from_serial = null;
            string to_serial = null;
            string customer = null;
            
            ComboboxItem item = new ComboboxItem();

            if (!DateTime.TryParse(this.dtExportDate.DateTime.Date.ToString(), out exporteddate))
            {
                error = "Please select Export Date";
            }

            if (string.IsNullOrEmpty(error))
            {
                if (this.cbeCompID.SelectedIndex >= 0)
                {
                    item = (ComboboxItem)this.cbeCompID.SelectedItem;
                    comp = item.Value.ToString();
                }
                else
                {
                    if (string.IsNullOrEmpty(this.cbeCompID.Text.Trim()))
                    {
                        error = "Please Select CompID";
                    }
                    else
                    {
                        for (int i = 0; i < this.cbeCompID.Properties.Items.Count; i++)
                        {
                            item = (ComboboxItem)this.cbeCompID.Properties.Items[i];
                            if (item.Value.ToString() == this.cbeCompID.Text.Trim())
                            {
                                comp = item.Value.ToString();
                            }
                        }
                        if (string.IsNullOrEmpty(comp))
                        {
                            error = "Invalid CompID";
                        }
                    }
                }
            }
            
            if (string.IsNullOrEmpty(error))
            {
                if (this.fromSerial.SelectedIndex >= 0)
                {
                    item = (ComboboxItem)this.fromSerial.SelectedItem;
                    from_serial = item.Value.ToString();
                }
                else
                {
                    if (!string.IsNullOrEmpty(this.fromSerial.Text.Trim()))
                    {
                        for (int i = 0; i < this.fromSerial.Properties.Items.Count; i++)
                        {
                            item = (ComboboxItem)this.fromSerial.Properties.Items[i];
                            if (item.Value.ToString() == this.fromSerial.Text.Trim())
                            {
                                from_serial = item.Value.ToString();
                            }
                        }
                    }
                }

                if (string.IsNullOrEmpty(from_serial))
                {
                    error = "From serial can not be null!. Please check again.";
                }
            }

            if (string.IsNullOrEmpty(error))
            {
                if (this.toSerial.SelectedIndex >= 0)
                {
                    item = (ComboboxItem)this.toSerial.SelectedItem;
                    to_serial = item.Value.ToString();
                }
                else
                {
                    if (!string.IsNullOrEmpty(this.toSerial.Text.Trim()))
                    {
                        for (int i = 0; i < this.toSerial.Properties.Items.Count; i++)
                        {
                            item = (ComboboxItem)this.toSerial.Properties.Items[i];
                            if (item.Value.ToString() == this.toSerial.Text.Trim())
                            {
                                to_serial = item.Value.ToString();
                            }
                        }
                    }
                }

                if (string.IsNullOrEmpty(to_serial))
                {
                    error = "To serial can not be null!. Please check again.";
                }
            }

            if (string.IsNullOrEmpty(error))
            {
                if (string.IsNullOrEmpty(txtRJPlanNo.Text))
                {
                    error = "RJ Plan No. can not be null!. Please check again.";
                }
            }

            if (string.IsNullOrEmpty(error))
            {
                if (string.IsNullOrEmpty(txtExportedBy.Text))
                {
                    error = "Exported by can not be null!. Please check again.";
                }
            }

            if (string.IsNullOrEmpty(error))
            {
                if (this.cbeCustomerID.SelectedIndex < 0)
                {
                    error = "Please Select Customer.";
                }
                else
                {
                    item = (ComboboxItem)this.cbeCustomerID.SelectedItem;
                    customer = item.Value.ToString();
                }
            }

            if (string.IsNullOrEmpty(error))
            {   
                try
                {
                    int recordupdated = 0;
                    myConnection.Open();
                    string sql = "UPDATE [231_RobotOrderDetail] SET Exported=1, ExportedDate=@exporteddate, "
                        + " RJNo='" + txtRJPlanNo.Text + "', "
                        + " ExportedBy='" + txtExportedBy.Text  + "', CustomerID='" + customer + "'"
                        + " WHERE (CompID=N'" + comp + "') AND (Exported=0) AND (SerialNo BETWEEN N'" + from_serial + "'"
                        + " AND N'" + to_serial + "')";
                    SqlCommand cmd_sql = new SqlCommand(sql, myConnection);
                    cmd_sql.Parameters.Add("@exporteddate", SqlDbType.DateTime).Value = exporteddate.Date;
                    recordupdated = cmd_sql.ExecuteNonQuery();
                    cmd_sql.Dispose();
                    myConnection.Close();
                    getSerialList();
                    MessageBox.Show("F4 Export successful " + recordupdated.ToString() + " record.");
                    clearForm();
                }
                catch (Exception ex)
                {
                    if (myConnection.State == ConnectionState.Open)
                    {
                        myConnection.Close();
                    }
                    MessageBox.Show(ex.Message);
                }                 
            }
            else
            {
                MessageBox.Show(error);
            }
        }        
        //////////////////////////////////////////
        /// Create Serial No List with selected Order No
        /////////////////////////////////////////////////
        private void getSerialList()
        {
            serialList.Clear();
            lbcSerialNo.DataSource = null;
            this.lbcSerialNo.Enabled = false;
            this.buttonAdd.Enabled = false;
            if (this.cbeCompID.SelectedIndex >= 0)
            {
                ComboboxItem comp = (ComboboxItem)this.cbeCompID.SelectedItem;
                try
                {
                    myConnection.Open();
                    SqlCommand cmd_sql = myConnection.CreateCommand();
                    cmd_sql.CommandText = "SELECT SerialNo FROM [231_RobotOrderDetail]"
                        + " WHERE (CompID='" + comp.Value + "')"
                        + " AND (Exported=0) AND (Finished=1)";
                    SqlDataReader dataReader = cmd_sql.ExecuteReader();
                    while (dataReader.Read())
                    {
                        serialList.Add(dataReader["SerialNo"].ToString().Trim());
                        ComboboxItem item = new ComboboxItem();
                        item.Value = dataReader["SerialNo"].ToString().Trim();
                        item.Text = dataReader["SerialNo"].ToString().Trim();
                        this.fromSerial.Properties.Items.Add(item);
                        this.toSerial.Properties.Items.Add(item);
                    }
                    dataReader.Close();
                    cmd_sql.Dispose();
                    myConnection.Close();

                    if (serialList.Count > 0)
                    {
                        lbcSerialNo.DataSource = serialList;
                        this.lbcSerialNo.Enabled = true;
                        this.buttonAdd.Enabled = true;
                    }
                }
                catch
                {
                    if (myConnection.State == ConnectionState.Open)
                    {
                        myConnection.Close();
                    }
                }
            }
        }
       
        private void cbeCompID_SelectedIndexChanged(object sender, EventArgs e)
        {
            getSerialList();            
        }
        private void clearForm()
        {
            foreach (Control c in this.Controls)
            {
                if (c.Name != "cbeCompID" && c.Name != "dtExportDate")
                {                    
                    if (c is DevExpress.XtraEditors.TextEdit)
                    {
                        ((DevExpress.XtraEditors.TextEdit)c).Text = null;
                    }

                    if (c is DevExpress.XtraEditors.ComboBoxEdit)
                    {
                        ((DevExpress.XtraEditors.ComboBoxEdit)c).SelectedIndex = -1;
                    }
                }
            }
        }
    }
}
